import React, { useCallback, useRef, useState } from 'react';
import { Button, Drawer, Form, Input, message, Popconfirm, Select, Space, Table } from 'antd';
import { ProTable, ProColumns, FooterToolbar } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchContractList, deleteContract, updateContract, downloadAttachment } from '@/services/ant-design-pro/contract';
import type { ActionType } from '@ant-design/pro-components';
import FileUpload from '@/components/FileUpload';

const { Option } = Select;

const ContractList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = Form.useForm();
  const { run: delRun, loading: deleteLoading } = useRequest(deleteContract, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败，请重试');
    },
  });

  const { run: updateRun } = useRequest(updateContract, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('更新成功');
    },
    onError: () => {
      message.error('更新失败，请重试');
    },
  });

  const handleRemove = useCallback(
    async (selectedRows: any[]) => {
      if (selectedRows.length === 0) {
        message.warning('请先选择要删除的项');
        return;
      }
      await delRun({ id: selectedRows.map((row) => row.id)[0] });
    },
    [delRun],
  );

  const handleSave = useCallback(
    async (values: any) => {
      if (currentRecord) {
        await updateRun({ ...currentRecord, ...values });
      }
      setDrawerVisible(false);
    },
    [currentRecord, updateRun],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      width: 100,
      ellipsis: true,
    },
    {
      title: '合同名称',
      dataIndex: 'contractName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '购买人姓名',
      dataIndex: 'buyerName',
      width: 100,
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 120,
      ellipsis: true,
    },
    {
      title: '账户类型',
      dataIndex: 'accountType',
      width: 100,
      ellipsis: true,
    },
    {
      title: '公司名称',
      dataIndex: 'companyName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '是否到期',
      dataIndex: 'expiryStatus',
      width: 100,
      ellipsis: true,
    },
    {
      title: '合同附件',
      dataIndex: 'attachment',
      width: 100,
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => downloadAttachment(record.id)}>下载</a>
      ),
    },
    {
      title: '购买时间',
      dataIndex: 'purchaseTime',
      width: 150,
      ellipsis: true,
    },
    {
      title: '到期时间',
      dataIndex: 'expiryTime',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      width: 180,
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            setCurrentRecord(record);
            setDrawerVisible(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue(record);
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="disable"
          title="确定禁用吗？"
          onConfirm={() => handleDisable(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <a>禁用</a>
        </Popconfirm>,
      ],
    },
  ];

  const handleDisable = async (id: number) => {
    await updateRun({ id, status: 'disabled' });
    actionRef.current?.reload();
  };

  return (
    <>
      <ProTable<any>
         scroll={{ x: 1300 }}
        headerTitle="合同管理列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        request={(params) => fetchContractList(params)}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            // Implement row selection if needed
          },
        }}
      />

      <Drawer
        title={currentRecord ? '合同详情' : '编辑合同'}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            {currentRecord && (
              <Button
                type="primary"
                onClick={() => {
                  form.validateFields().then(handleSave);
                }}
              >
                保存
              </Button>
            )}
          </Space>
        }
      >
        <Form form={form} layout="vertical" initialValues={currentRecord}>
          <Form.Item label="编号" name="id">
            <Input readOnly />
          </Form.Item>
          <Form.Item label="合同名称" name="contractName">
            <Input />
          </Form.Item>
          <Form.Item label="购买人姓名" name="buyerName">
            <Input />
          </Form.Item>
          <Form.Item label="手机号" name="phone">
            <Input />
          </Form.Item>
          <Form.Item label="账户类型" name="accountType">
            <Select>
              <Option value="个人">个人</Option>
              <Option value="企业">企业</Option>
            </Select>
          </Form.Item>
          <Form.Item label="公司名称" name="companyName">
            <Input />
          </Form.Item>
          <Form.Item label="是否到期" name="expiryStatus">
            <Select>
              <Option value="未到期">未到期</Option>
              <Option value="已到期">已到期</Option>
              <Option value="即将到期">即将到期</Option>
            </Select>
          </Form.Item>
          <Form.Item label="合同附件" name="attachment">
            <FileUpload value={form.getFieldValue('attachment')} onChange={(url) => form.setFieldsValue({ attachment: url })} />
          </Form.Item>
          <Form.Item label="购买时间" name="purchaseTime">
            <Input readOnly />
          </Form.Item>
          <Form.Item label="到期时间" name="expiryTime">
            <Input readOnly />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  );
};

export default ContractList;